﻿using System;
using System.Web;
using Com.Binaria.Core.Web;
using Com.Binaria.SISCOB.Web.Model;
using System.Collections.Generic;
using Com.Binaria.SISCOB.Funcional.DTO;
using System.Text;
using System.Web.Script.Serialization;
using Com.Binaria.Core.Dto;
using System.Diagnostics;

namespace Com.Binaria.SISCOB.Web.Presenter
{
    public class ManttoPresenter<TDto> : APresenter<TDto> where TDto : class
    {
        /// <summary>
        /// Retorna la informacion para todos los items en formato JSON
        /// </summary>
        /// <param name="oGridRequest">Parametros de Consulta</param>
        protected override IList<TDto> GetDataAllJSON(GridRequest oGridRequest)
        {
            //Recuperar informacion a enviar
            string sortName = (oGridRequest.SortName != null ? oGridRequest.SortName : null);
            string sortOrder = (oGridRequest.SortOrder != null ? oGridRequest.SortOrder.ToUpper() : null);
            IList<TDto> oLst = GetDataAllPag(oGridRequest.Page, oGridRequest.RowsPage, sortName, sortOrder);

            return oLst;
        }

        /// <summary>
        /// Retorna la informacion para todos los items de acuerdo a la informacion proporcionada, en formato JSON
        /// </summary>
        /// <param name="oTable">Parametros de Filtrado</param>
        protected override IList<TDto> GetDataByJSON(GridRequest oGridRequest)
        {
            Dictionary<string, object> oTable = (Dictionary<string, object>)oGridRequest.QueryEntity;
            StringBuilder sb_ = new StringBuilder(16);
            foreach (KeyValuePair<string, object> item in oTable)
            {
                if (item.Value is string)
                {
                    if (sb_.Length > 0) sb_.Append(",");
                    sb_.Append(string.Format(" \"{0}\" : \"{1}\" ", item.Key, item.Value));
                }
            }
            if (sb_.Length < 2) return null;
            sb_.Insert(0, "{");
            sb_.Append("}");
            //
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            TDto oDto = serializer.Deserialize<TDto>(sb_.ToString());
            
            if (oDto is PaginadoDTO)
            {
                (oDto as PaginadoDTO).Pagina = oGridRequest.Page;
                (oDto as PaginadoDTO).SizePagina = oGridRequest.RowsPage;
                (oDto as PaginadoDTO).ColumnOrden = oGridRequest.SortName;
                (oDto as PaginadoDTO).TipoOrden = oGridRequest.SortOrder;
            }
            //Recuperar informacion a enviar
            IList<TDto> oLst = GetDataByPag(oDto);
            //
            return oLst;
        }


        /// <summary>
        /// Metodo destinado a recuperar todos los items
        /// </summary>
        /// <returns>Conjunto de datos</returns>
        protected IList<TDto> GetDataAllPag(int page, int pageSize, string sortName, string sortOrder)
        {
            IList<TDto> oList = null;

            IRepository<TDto> oRep = Repositorios[IdentityName] as IRepository<TDto>;

            if (oRep != null)
            {
                if (oRep is CartolaRepository)
                {
                    CartolaFuncionalDTO cartolaFDTO = new CartolaFuncionalDTO() { Pagina = page, SizePagina = pageSize, ColumnOrden = sortName, TipoOrden = sortOrder };
                    oList = ((CartolaRepository)oRep).GetAllPag(cartolaFDTO) as IList<TDto>;
                }
                else if (oRep is CartolaMayorRepository)
                {
                    CartolaMayorFuncionalDTO cartolaMayorFDTO = new CartolaMayorFuncionalDTO() { Pagina = page, SizePagina = pageSize, ColumnOrden = sortName, TipoOrden = sortOrder };
                    oList = ((CartolaMayorRepository)oRep).GetAllPag(cartolaMayorFDTO) as IList<TDto>;
                }
                else if (oRep is EgresoRepository)
                {
                    EgresoFuncionalDTO egresoFDTO = new EgresoFuncionalDTO() { Pagina = page, SizePagina = pageSize, ColumnOrden = sortName, TipoOrden = sortOrder };
                    oList = ((EgresoRepository)oRep).GetAllPag(egresoFDTO) as IList<TDto>;
                }
                else if (oRep is IngresoRepository)
                {
                    IngresoFuncionalDTO ingresoFDTO = new IngresoFuncionalDTO() { Pagina = page, SizePagina = pageSize, ColumnOrden = sortName, TipoOrden = sortOrder };
                    oList = ((IngresoRepository)oRep).GetAllPag(ingresoFDTO) as IList<TDto>;
                }
                else
                {
                    //*** Comprobar CACHE
                    //string sKey = string.Format("__{0}__", IdentityName);
                    //oList = (IList<TDto>)HttpContext.Current.Cache[sKey];
                    //if (oList == null)
                    //{
                        oList = oRep.GetAll();
                    //}
                    //*** Administrar CACHE
                    //HttpContext.Current.Cache.Insert(sKey, oList, null, DateTime.Now.AddMinutes(3), TimeSpan.Zero);
                }
            }
            //
            return oList;
        }

        /// <summary>
        /// Metodo destinado a recuperar los items basado en nullables
        /// </summary>
        /// <returns>Conjunto de datos</returns>
        protected IList<TDto> GetDataByPag(TDto item)
        {
            if (item == null)
                throw new Com.Binaria.Core.Exceptions.ManagerException("El objeto a registrar no puede ser Nulo", TraceEventType.Warning);

            IList<TDto> oRet = null; // default(IList<TDto>);
            //
            IRepository<TDto> oRep = Repositorios[IdentityName] as IRepository<TDto>;

            if (oRep is CartolaRepository)
            {
                if (oRep != null) oRet = ((CartolaRepository)oRep).GetByPag(item as CartolaFuncionalDTO) as IList<TDto>;
            }
            else if (oRep is CartolaMayorRepository)
            {
                if (oRep != null) oRet = ((CartolaMayorRepository)oRep).GetByPag(item as CartolaMayorFuncionalDTO) as IList<TDto>;
            }
            else if (oRep is EgresoRepository)
            {
                if (oRep != null) oRet = ((EgresoRepository)oRep).GetByPag(item as EgresoFuncionalDTO) as IList<TDto>;
            }
            else if (oRep is IngresoRepository)
            {
                if (oRep != null) oRet = ((IngresoRepository)oRep).GetByPag(item as IngresoFuncionalDTO) as IList<TDto>;
            }
            else
            {
                if (oRep != null) oRet = oRep.GetBy(item);
            }
            //
            return oRet;
        }

    }
}